# -*- coding: utf-8 -*-

import os
import sys
import jinja2
import simplejson
import time
from openerp import http
from openerp.http import request
from openerp.osv import osv
from openerp.addons.website_mshop.pools import ModelPool, CursorProxy, common_functions, PageProxy, _slug
from weixin_enterprise import WeixinEnterprise
import datetime

SUPERUSER_ID = 1
if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


class WxAppApproval(WeixinEnterprise):
    _app_xml_id = 'dftg_weixin.weixin_dftg_weixin_approval'


class WxAppApprovalController(http.Controller):
    weixin_app = None

    def __init__(self):
        env.globals['_pool'] = ModelPool()
        env.globals['_cr'] = CursorProxy()
        env.globals['_page'] = PageProxy()
        env.globals['_slug'] = _slug
        env.globals.update(common_functions)
        env.filters['tojson'] = simplejson.dumps
        self.weixin_app = WxAppApproval()

    # 微信回调入口网址
    @http.route('/weixin/app/punch', auth='public')
    def weixin(self, **kw):
        result = self.weixin_app.process(request.httprequest.args, request.httprequest.data)
        return result


class weixin_approval(osv.osv):
    _inherit = 'weixin.approval'

    def get_all_approval_data(self, cr, uid, input_start_time=False, input_end_time=False, context=None):
        t = time.localtime(time.time() - 7 * 86400)
        time_start = time.mktime(
            time.strptime(input_start_time or time.strftime('%Y-%m-01 00:00:00', t), '%Y-%m-%d %H:%M:%S'))
        time_end = time.mktime(
            time.strptime(input_end_time or time.strftime('%Y-%m-%d 23:59:59', time.localtime(time.time())
                                                          ), '%Y-%m-%d %H:%M:%S'))

        starttime = long(time_start)
        endtime = long(time_end)
        wxappaproval = WxAppApprovalController()
        users = wxappaproval.weixin_app.wxapi.department_users(1, fetch_child=1)
        if users[0] and users[0].get('errcode') == 0:
            all_users = [user.get('userid') for user in users[0].get('userlist', [])]
        all_record = wxappaproval.weixin_app.wxapi.get_all_approval_data(starttime, endtime)
        if all_record and all_record[0].get('count', 0) > 0:
            for approval in all_record[0].get('data'):
                approval_ids = self.search(cr, uid, [('sp_num', '=', approval.get('sp_num')),
                                                     ('sp_status', '=', approval.get('sp_status', 0))], context=context)
                # 如果审批单号已经存在则不再更新
                if approval_ids:
                    continue
                if approval.get('apply_user_id', 0) not in all_users:
                    continue
                approval.update({'apply_user_id': int(approval.get('apply_user_id', 0)),
                                 'approval_name': '、'.join(approval.get('approval_name', {})),
                                 'notify_name': '、'.join(approval.get('notify_name', {})),
                                 })
                if approval.get('sp_status', 0) == 2:
                    apply_data_str = approval.get('comm', {}).get('apply_data', '').replace('true', 'True').replace('false', 'False') or '{}'
                    apply_data = eval(apply_data_str)
                    if approval.get('leave', False):
                        approval.update({'start_time': approval.get('leave', {}).get('start_time', 0),
                                         'end_time': approval.get('leave', {}).get('end_time', 0),
                                         'leave_type': approval.get('leave', {}).get('leave_type', 0),
                                         'duration': str(approval.get('leave', {}).get('duration', 0)),
                                         'reason': approval.get('leave', {}).get('reason', 0)})
                        del approval['leave']
                    elif apply_data and apply_data.get('item-1497417335175'):
                        ### 补卡相关的审批
                        if apply_data.get('begin_time'):
                            approval.update(
                                {'start_time':  int(apply_data.get('begin_time', {'value': 0}).get('value')) / 1000,
                                 'end_time':  int(apply_data.get('end_time', {'value': 0}).get('value')) / 1000,
                                 'duration': str(int(apply_data.get('duration', {'duration': {}}).get('value', '0')) / 3600),
                                 'reason': apply_data.get('item-1497417335175', {'value': ''}).get('value'),
                                 'leave_type': 9,
                                 })
                        elif apply_data.get('checkin-time'):
                            date_int = apply_data.get('checkin-time', {'value': 0}).get('setvalue')/1000
                            if date_int:
                                dateArray = datetime.datetime.utcfromtimestamp(date_int)
                                otherStyleTime = dateArray.strftime('%Y-%m-%d %H:%M:%S')
                                if otherStyleTime[11:] > '12:00:00':
                                    approval.update({'start_time': str(apply_data.get('checkin-time', {'value': 0}).get(
                                                         'setvalue') / 1000)})
                                else:
                                    approval.update({'end_time': str(apply_data.get('checkin-time', {'value': 0}).get(
                                        'setvalue') / 1000)})
                            approval.update({'reason': apply_data.get('item-1497417335175', {'value': ''}).get('value'),
                                             'leave_type':  9,
                                             })
                    elif apply_data and apply_data.get('item-1497581590290'):
                        approval.update(
                            {'start_time': int(apply_data.get('begin_time', {'value': 0}).get('value')) / 1000,
                             'end_time': int(apply_data.get('end_time', {'value': 0}).get('value')) / 1000,
                             'duration': str(int(apply_data.get('duration', {'duration': {}}).get('value', '0')) / 3600),
                             'reason': apply_data.get('item-1497581558567', {'value': ''}).get('value'),
                             'leave_type': 10,
                             })
                    else:
                        continue
                    try:
                        self.create(cr, uid, approval, context=context)
                    except BaseException as excep:
                        print excep
        return True

